package com.swf.seed.os.command.impl;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import com.swf.seed.base.SdLetter;
import com.swf.seed.os.annotation.Command;
import com.swf.seed.os.command.ICommand;

/**
 *
 * Command适配器
 * 
 * @author Weifeng Shen
 * @since 2016年7月20日
 * @see ICommand
 */
public abstract class CommandAdaptor implements ICommand {
	
	/**
	 * 帮助头部描述
	 */
	protected StringBuilder header = new StringBuilder("\r\n");
	/**
	 * 帮助底部描述
	 */
	protected StringBuilder footer = new StringBuilder("\r\nAUTHOR\r\n  Written by Weifeng Shen.");
	
	/**
	 * 命令参数
	 */
	protected Options options = new Options( ); 
	
	public String getHeader() {
		return header.toString();
	}
	
	public String getFooter() {
		return footer.toString();
	}
	
	public Options getOptions() {
		// TODO Auto-generated method stub
		return options;
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.swf.seed.os.command.ICommand#execute(java.lang.String[])
	 */
	@Override
	public final void execute(String[] args) throws ParseException {
		List<String> argList = Arrays.asList(args);
		option();
		if (argList.contains("-h")) {

			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp(this.getClass().getAnnotation(Command.class)
					.value(),header.toString(), options,footer.toString(),true);
			return;
		}
		CommandLineParser parser = new DefaultParser();
		CommandLine commandLine = parser.parse(options, args);
		try {
			customizedExecute(commandLine);
		} catch (Exception e) {
			throw new ParseException(e.getMessage());
		}
	}

	/**
	 * 个性化命令执行
	 * 
	 * @param commandLine
	 *            命令
	 * @throws ParseException
	 */
	abstract void customizedExecute(CommandLine commandLine) throws Exception;
}
